//
//  FMNetwork.swift
//  FMRadio
//
//  Created by 范东 on 2022/7/27.
//

import UIKit
import FDNetwork
import FDUIKit
import Alamofire

class FMNetwork: NSObject {
    class func GET(url : String, param : [String : String]?, success : @escaping ((Any)->()), failure : @escaping ((String)->())) {
        FMNetwork.HTTP(method: .get, url: url, param: param, success: success, failure: failure)
    }
    
    class func POST(url : String, param : [String : String]?, success : @escaping ((Any)->()), failure : @escaping ((String)->())) {
        FMNetwork.HTTP(method: .post, url: url, param: param, success: success, failure: failure)
    }
    class private func HTTP(method: HTTPMethod, url : String, param : [String : String]?, success : @escaping ((Any)->()), failure : @escaping ((String)->())){
        if NetworkReachabilityManager()?.isReachable ?? false {
            var newParam = param
            newParam?["token"] = UserDefaults.standard.string(forKey: .tokenKey)
            FDNetwork.HTTP(method:method ,url: url, header:[:], param: newParam) { result in
                guard let resultDict = result as? [String: Any] else{
                    failure("返回数据格式不正确")
                    return
                }
                let ret = resultDict["ret"] as! Int
                if ret != 200 {
                    failure(resultDict["msg"] as! String)
                }else{
                    success(resultDict["data"]!)
                }
            } failure: { error in
                failure(error)
            }
        }else{
            FDMessageView.show(title: NSLocalizedString("No network", comment: ""), message: NSLocalizedString("Please connect to network(cellar or WiFi)", comment: ""), theme: .error)
        }
    }
}
